package com.yungu.swift.order.utils;


import com.yungu.swift.lbs.model.dto.LatLngDto;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/1/14.
 */
public class PolylineUtils {

    /**
     * @param path 经纬度集合
     * @return 加密字符串
     */
    public static String encodePoly(final List<LatLngDto> path) {
        long lastLat = 0;
        long lastLng = 0;

        final StringBuffer result = new StringBuffer();

        for (final LatLngDto point : path) {
            long lat = Math.round(point.getLatitude() * 1E5);
            long lng = Math.round(point.getLongitude() * 1E5);

            long dLat = lat - lastLat;
            long dLng = lng - lastLng;

            encode(dLat, result);
            encode(dLng, result);

            lastLat = lat;
            lastLng = lng;
        }
        return result.toString();
    }

    private static void encode(long v, StringBuffer result) {
        v = v < 0 ? ~(v << 1) : v << 1;
        while (v >= 0x20) {
            result.append(Character.toChars((int) ((0x20 | (v & 0x1f)) + 63)));
            v >>= 5;
        }
        result.append(Character.toChars((int) (v + 63)));
    }

    /**
     * @param encoded 加密字符串
     * @return 经纬度集合
     */
    public static List<LatLngDto> decodePoly(String encoded) {
        List<LatLngDto> poly = new ArrayList();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dLat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dLat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dLng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dLng;

            LatLngDto p = new LatLngDto((((double) lat / 1E5)), (((double) lng / 1E5)));
            poly.add(p);
        }
        return poly;
    }
}
